package com.zang.test.dubbo.aspect;

import com.zang.test.cache.RedissonLockHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Zhang Qiang
 * @date 2019/10/29 11:05
 */
@Slf4j
@Aspect
@Component
public class ServiceAspect {

    private final String QUEUE_QR_CODE = "topic-1";

    @Autowired
    RedissonLockHandler redissonLockHandler;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Pointcut("execution(public * com.zang.test.dubbo.service.*.*(..))")
    public void implCut(){
    }

    @Around("implCut()")
    public Object ImplArount(ProceedingJoinPoint joinPoint){
        Object callBack = null;
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        String mName = method.getName();
        RLock rLock = redissonLockHandler.getRLock(mName);
        try {
            rLock.lock();
            callBack = joinPoint.proceed();
        } catch (Throwable throwable) {
            log.info(" sendMessage exception {}", throwable.getMessage());
        } finally {
            log.info(" 切点方法 ", mName);
            sendMessage(QUEUE_QR_CODE, "执行 " + mName);
            rLock.unlock();
        }
        return callBack;

    }

    private void sendMessage(String topic, String message){
        rocketMQTemplate.asyncSend(topic, message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("send message success, msgID : {}, mseContent : {}", sendResult.getMsgId(), sendResult.getMessageQueue());
            }
            @Override
            public void onException(Throwable throwable) {
                log.info("sendMessage exception {}", throwable.getMessage());
            }
        });
    }




}
